package cc.eddic.pratice.programmingparadigms.exam.impl;

import cc.eddic.pratice.programmingparadigms.exam.Model.AnswerModel;
import cc.eddic.pratice.programmingparadigms.exam.QuestionBankService;
import cc.eddic.pratice.programmingparadigms.exam.QuestionType;
import cc.eddic.pratice.programmingparadigms.exam.domain.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class QuestionBankServiceTyqImpl extends QuestionBankServiceImpl implements QuestionBankService {

    private static final Logger log = LoggerFactory.getLogger(QuestionBankServiceTyqImpl.class);

    @Override
    public List<Question> importQuestions(String questionTextFile) {
        List<Question> qList = new ArrayList<>();
        String questions = getQuestionFileContent();
        String[] questionsArray = questions.split("\n");
        for (String qStr : questionsArray) {
            if (qStr.length() == 0) {
                continue;
            }
            if (Character.isDigit(qStr.charAt(0))) {
                String[] subQuestion = qStr.split("、");
                qList.add(new Question(Integer.parseInt(subQuestion[0]), subQuestion[1], QuestionType.SINGLE_CHOICE));
            }
            if ((qStr.charAt(0) >= 'a' && qStr.charAt(0) <= 'z') || (qStr.charAt(0) >= 'A' && qStr.charAt(0) <= 'Z')) {
                String[] subQuestion = qStr.split("、");
                if (!qList.isEmpty()) {
                    qList.get(qList.size() - 1).add(new Option(subQuestion[1], subQuestion[0].charAt(0), false));
                }
            }
        }
        return qList;
    }

    //在Question列表的每一个Question里标出正确的Option
    @Override
    public List<Question> importCorrectAnswers(String correctAnswerTextFile) {
        List<Question> questionList = importQuestions(" ");
        Map<Integer, Character> answer = readCorrectAnswers2(" ");
        for (Question q : questionList) {
            if (!answer.containsKey(q.getNo())) {
                continue;
            }
            char choice = answer.get(q.getNo());//???????
            Option option = q.getOptions().stream()
                    .filter(o -> o.getChoice() == choice)
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("找不到第" + q.getNo() + "题的" + choice + "选项"));
            option.changeToCorrectAnswer();
            System.out.println("正确选项设置成功" + option.getQuestion().getNo() + option.getChoice() + ":" + option.isCorrectAnswer());
        }
        return questionList;
    }

    //正确答案存为 Map
    public Map<Integer, Character> readCorrectAnswers2(String correctAnswerTextFile) {
        Map<Integer, Character> result = new HashMap<>();
        String[] lines = getAnswerFileContent().split("\n");
        for (int i = 0; i < lines.length; i += 2) {
            String[] nos = lines[i].split("\t");
            String[] choices = lines[i + 1].split("\t");
            for (int j = 0; j < nos.length; j++) {
                String no = nos[j];
                String choice = choices[j];
                result.put(Integer.parseInt(no), choice.charAt(0));
            }
        }
        return result;
    }

    //正确答案存为 AnswerModel
    @Override
    public List<AnswerModel> readCorrectAnswers(String correctAnswerTextFile) {
        List<AnswerModel> answerModels = new ArrayList<>();
        String[] answer = getAnswerFileContent().split("\n");
        List<Integer> num = new ArrayList<>();
        List<Character> cha = new ArrayList<>();
        for (int i = 0; i < answer.length; i++) {
            String[] number = answer[i].split("\t");
            if (i % 2 == 0) {
                for (String str : number) {
                    int subNum = Integer.parseInt(str);
                    num.add(subNum);
                }
            } else {
                for (String str : number) {
                    char subCha = str.charAt(0);
                    cha.add(subCha);
                }
            }
        }
        for (int i = 0; i < num.size(); i++) {
            answerModels.add(new AnswerModel(num.get(i), cha.get(i)));
        }
        return answerModels;
    }

    //计算每个学生的成绩
    public Map<String, Integer> gradeCount() {
        Map<String, Integer> gradeMap = new HashMap<>();
        ExamServiceTyqImpl examServiceTyq = new ExamServiceTyqImpl();
        List<Answer> answerList = examServiceTyq.importAnswers(" ");
        //Stream方法计算学生成绩??????????????????????????????????
       return answerList.stream()
                .filter(answer -> answer.getChoice()==answer.getQuestion().getOptions().stream().filter(Option::isCorrectAnswer).findFirst().orElseThrow(()->new IllegalArgumentException("找不到第"+answer.getQuestion().getNo()+"题的正确答案")).getChoice())
                .collect(Collectors.groupingBy(answer -> answer.getStudent().getName(),Collectors.counting()))
               .entrySet().stream()
//               .map(en->en.getValue().intValue())
               .collect(Collectors.toMap(Map.Entry::getKey,e->e.getValue().intValue()));
        //原始方法计算学生成绩
//        for (Answer answer : answerList) {
//            if (!gradeMap.containsKey(answer.getStudent().getName())) {
//                gradeMap.put(answer.getStudent().getName(), 0);
//            }
//            char c = answer.getChoice();
//            Option option = answer.getQuestion().getOptions().stream()
//                    .filter(Option::isCorrectAnswer)// o->o.isCorrectAnswer()
//                    .findFirst()
//                    .orElseThrow(() -> new IllegalArgumentException("找不到第" + answer.getQuestion().getNo() + "的正确答案"));
//            if (option.getChoice() == c) {
//                gradeMap.put(answer.getStudent().getName(), gradeMap.get(answer.getStudent().getName()) + 4);
//            }
//
//        }
//        return gradeMap;
    }


    @Override
    public List<Question> importCategories(String categoryExcelFile) {
        try {
            HashMap<String, String> categoryMap = new HashMap<>();
            categoryMap.put("基础", "软件开发基础");
            categoryMap.put("HTML", "软件开发基础");
            categoryMap.put("SQL", "软件开发基础");
            categoryMap.put("DOS", "软件开发基础");
            categoryMap.put("Linux", "软件开发基础");
            categoryMap.put("数学", "软件开发基础");

            categoryMap.put("Word", "办公软件");
            categoryMap.put("Excel", "办公软件");

            categoryMap.put("代码", "代码");


            FileInputStream file = new FileInputStream(categoryExcelFile);
            Workbook workbook = new XSSFWorkbook(file);

            ArrayList<Question> questionList = (ArrayList<Question>) importCorrectAnswers("");


            Sheet categorySheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = categorySheet.rowIterator();

            rowIterator.next();
            Row rowSubCategory = rowIterator.next();

            while(rowIterator.hasNext()) {
                try {
                    Row row = rowIterator.next();
                    CellType cellType = row.getCell(0).getCellType();
                    if (cellType == CellType.STRING) {
                        break;
                    }
                    int no =  (int) row.getCell(0).getNumericCellValue();


                    Iterator<Cell> cellIterator = row.cellIterator();
//                    cellIterator.next();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        if (cell.getNumericCellValue() == 1) {
                            int columnIndex = cell.getColumnIndex();
                            String nameSubCategory = rowSubCategory.getCell(columnIndex).getRichStringCellValue().getString();
                            SubCategory subcategory = new SubCategory(nameSubCategory);
                            subcategory.setCategory(new Category(categoryMap.get(nameSubCategory)));
                            questionList.get(no - 1).setSubCategory(subcategory);
                            break;
                        }
                    }

                }
                catch (NumberFormatException e) {
                    break;
                }
            }

            return questionList;
        }
        catch (FileNotFoundException e) {
            log.error("importCategories FileInputStream FileNotFoundException\n");
        } catch (IOException e) {
            log.error("importCategories XSSFWorkbook IOException\n");
        }
        return null;
    }
}


